package tgc.edu.ljc.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import tgc.edu.ljc.custom.BCryptPasswordEncoder2;
import tgc.edu.ljc.service.SysUserService;



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	private SysUserService sysUserService;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.userDetailsService(sysUserService)  	
			.passwordEncoder(new BCryptPasswordEncoder2());
		auth.inMemoryAuthentication().withUser("aaa").password("{noop}1234").roles("DIY","ADMIN");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//安全器令牌
	 	http.csrf().disable();
	 	http.headers().frameOptions().disable();    //解决iframe与安全器兼容性问题
		http.formLogin()
				//登录请求被拦截
				.loginPage("/login").permitAll()
				.usernameParameter("pig")
				.passwordParameter("dog")   
				//设置默认登录成功跳转页面
				.successForwardUrl("/main")
				//登录失败的页面
				.failureUrl("/login?error");
        http.authorizeRequests().antMatchers("/static/**","/assets/**","/media/**").permitAll();    //文件下的所有都了能访问
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().antMatchers("/app/**").permitAll();
        http.authorizeRequests().antMatchers("/sysFile/app/**").permitAll();
        http.logout().logoutUrl("/logout").permitAll();     //退出
        http.authorizeRequests().anyRequest().authenticated();    //除此之外的都必须通过请求验证才能访问
	}
}
